package com.knxhd.controller;

import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.knxhd.pojo.LlmModelConfig;
import com.knxhd.service.McpService;
import com.knxhd.utils.LangChain4jUtil;

import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.http.HttpMcpTransport;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolProvider;
import reactor.core.publisher.Flux;

/*
 * @author: tianluhua
 * @Date: 2025-07-16 18:53:38
 * @Description: 
 * @version: V1.0.0
 */
@RestController
@RequestMapping("/v1/chat")
public class McpChatController {

    @GetMapping(value = "/complations")
    public Flux<String> chatComplations(String query, ServerWebExchange webExchange) {
        webExchange.getResponse().getHeaders().setContentType(MediaType.TEXT_EVENT_STREAM);
        LlmModelConfig llmModelConfig = new LlmModelConfig();
        llmModelConfig.setApi("https://ark.cn-beijing.volces.com/api/v3");
        llmModelConfig.setModelId("deepseek-v3-250324");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Authorization", "Bearer e6601829-1671-4d5c-9d04-49bde63d7a54");
        llmModelConfig.setHeader(jsonObject.toJSONString());

        StreamingChatModel streamingChatModel = LangChain4jUtil.streamingLanguageModelBulider(llmModelConfig);

        McpTransport transport = new HttpMcpTransport.Builder()
                .sseUrl("https://mcp.amap.com/sse?key=338aa59c5214de76799e74f9fda693e2") // SSE 通道 URL
                .logRequests(true) // 开启请求日志
                .logResponses(true) // 开启响应日志
                .build();
        McpClient mcpClient = new DefaultMcpClient.Builder()
                .transport(transport)
                .build();
        ToolProvider toolProvider = McpToolProvider.builder()
                .mcpClients(List.of(mcpClient))
                .build();
        McpService mcpService = AiServices.builder(McpService.class)
                .streamingChatModel(streamingChatModel)
                .toolProvider(toolProvider)
                .build();

        return mcpService.chat(query);
    }
}
